package config

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"
)

var AdxRedisDb *redis.Pool

func InitAdxRedis() {
	AdxRedisDb = RedisConn(GConfig.RedisAPI)
}
func RedisConn(value Config_redis) *redis.Pool {
	c := &redis.Pool{
		Wait: false,
		// 最大空闲链接
		MaxIdle: 10,
		// 最大激活链接
		MaxActive: 1000,
		// 最大空闲链接等待时间
		//IdleTimeout: time.Duration(2) * time.Second,
		IdleTimeout: time.Duration(5*60) * time.Second,
		Dial: func() (redis.Conn, error) {
			rc, err := redis.Dial("tcp", value.Server)
			//fmt.Println(m.Server + ":" + m.Port)
			if err != nil {
				fmt.Println("redis connect err001:", err.Error())
				return nil, err
			}
			if value.PassPort != "" {
				_, err = rc.Do("AUTH", value.PassPort)
				if err != nil {
					fmt.Println("redis auth failed:" + value.PassPort)
					time.Sleep(time.Millisecond * 200)
					_, err = rc.Do("AUTH", value.PassPort)
				}
				if err != nil {
					fmt.Println("redis connect err002:", err.Error())
					return nil, err
				}
			}
			if value.Db > 0 {
				_, _ = rc.Do("SELECT", value.Db)
				//fmt.Println("USE DB", c.DB)
			}
			return rc, nil
		},
	}
	c.Get().Do("ping")
	c.TestOnBorrow = func(c redis.Conn, t time.Time) error {
		_, err := c.Do("PING")
		return err
	}
	return c
}
